import logging
import time
from selenium.webdriver.support.wait import WebDriverWait
from config import BASE_DIR
from utils import DriverUtil


class BasePage:
    def __init__(self):
        self.driver = DriverUtil.get_driver()

    def find_el(self, loc, timeout=10):
        try:
            el = WebDriverWait(self.driver, timeout).until(lambda x: x.find_element(*loc))
            return el
        except Exception as e:
            logging.error(f"查找元素{loc}失败")
            self.save_screenshot("找不到元素")
            raise e

    def find_els(self, loc, timeout=10):
        els = WebDriverWait(self.driver, timeout).until(lambda x: x.find_elements(*loc))
        return els

    def click_el(self, loc, timeout=10):
        try:
            el = self.find_el(loc, timeout)
            el.click()
        except Exception as e:
            logging.error(f"点击元素{loc}失败")
            self.save_screenshot("无法点击元素")
            raise e

    def input_content(self, loc, content, timeout=10):
        try:
            el = self.find_el(loc, timeout)
            el.clear()
            el.send_keys(content)
        except Exception as e:
            logging.error(f"元素{loc}输入内容失败")
            self.save_screenshot("元素无法输入内容")
            raise e

    def switch_to_iframe(self, loc, timeout=10):
        try:
            iframe = self.find_el(loc, timeout)
            self.driver.switch_to.frame(iframe)
        except Exception as e:
            logging.error(f"切换元frame至素{loc}失败")
            self.save_screenshot("无法切换到iframe元素")
            raise e

    def get_url(self, url):
        self.driver.get(url)

    def save_screenshot(self, img_doc):
        """
        页面截屏保存截图
        :param img_doc: 截图说明
        :return:
        """
        # time.strftime("%Y:%m:%d%:%H:%M:%S")
        # file_name = BASE_DIR + f"/screen/{datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')}_{img_doc}.png"
        file_name = BASE_DIR + f"/screen/{time.strftime('%Y-%m-%d_%H-%M-%S')}_{img_doc}.png"
        self.driver.save_screenshot(file_name)
        logging.info("页面截图文件保存在：{}".format(file_name))
